﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq.Expressions;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using CamlexNET;
using LifeInSharePoint.Common;
using LifeInSharePoint.Common.Base;
using Microsoft.SharePoint;
using System.Web.UI.HtmlControls;

namespace LifeInSharePoint.Blog.Common.WebParts.LISPBlogGallery
{
    [ToolboxItemAttribute(false)]
    public class LISPBlogGallery : BaseWebPart
    {

        #region Private Properties

        private const string GALLERYLIST = "Blog Gallery";
        private const string CONTENTTYPE = "Life In SharePoint Blog Gallery";
        private string transformedXML = null;
        private bool errorFound = false;
        private string errorMessage = null;
        private string photoAlbum = string.Empty;

        #endregion

        private string _XSLTPath = "/_layouts/LifeInSharePoint.Blog/xslt/Gallery.xslt";
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Life In SharePoint")]
        [WebDisplayName("XSLT Path")]
        [WebDescription("Path the the XSLT")]
        public string XSLTPath
        {
            get { return _XSLTPath; }
            set { _XSLTPath = value; }
        }




        protected override void OnInit(EventArgs e)
        {
            this.ChromeType = PartChromeType.None;
            this.ExportMode = WebPartExportMode.All;
            photoAlbum = SPQueryStringHelper.GetQueryStringItem(HttpContext.Current.Request.QueryString, "Album", String.Empty);
            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!string.IsNullOrEmpty(XSLTPath))
            {
                processData();
            }
            else
            {
                errorFound = true;
                errorMessage = "XSLT Path is not Defined - Please edit webpart Properties";
            }

        }

        protected override void CreateChildControls()
        {
            if (!errorFound)
            {
                HtmlGenericControl container = new HtmlGenericControl("Div");
                container.InnerHtml = transformedXML;
                this.Controls.Add(container);
            }
            else
            {
                Label errorMsg = new Label();
                errorMsg.Text = errorMessage;
                this.Controls.Add(errorMsg);
            }

        }

        private void processData()
        {
            //Get the SP Web
            SPWeb web = SPContext.Current.Site.RootWeb;

            //Get the List Instance
            SPList newslist = web.Lists[GALLERYLIST];

            //Get a new SPQuery Instance
            SPQuery workQuery = new SPQuery();
            //Create Expressions for the CAMLEx
            var expressions = new List<Expression<Func<SPListItem, bool>>>();

            if (!string.IsNullOrEmpty(photoAlbum))
            {
                expressions.Add(x => x["LISPBlogGalleryAlbum"] == (DataTypes.LookupValue)photoAlbum);
            }
            expressions.Add(x => ((string)x["ContentType"]) == CONTENTTYPE);
            var caml = Camlex.Query().WhereAll(expressions).ToString();

            workQuery.Query = caml + "<OrderBy><FieldRef Name='Modified' Ascending='False'/></OrderBy>";

            SPListItemCollection _workItemCollection = newslist.GetItems(workQuery);

            if (_workItemCollection != null && _workItemCollection.Count > 0)
            {
                DataTable PhotoDT = new DataTable("Photo");
                PhotoDT.Columns.Add("ID");
                PhotoDT.Columns.Add("Title");
                PhotoDT.Columns.Add("Image");
                PhotoDT.Columns.Add("Thumbnail");
                PhotoDT.Columns.Add("Order");

                foreach (SPListItem _workItem in _workItemCollection)
                {
                    string Title = SPListHelper.GetColumnStringValue(_workItem, "Title");
                    string ContentType = SPListHelper.GetColumnStringValue(_workItem, "ContentType");
                    int ID = SPListHelper.GetColumnIntValue(_workItem, "ID");
                    string Url = SPListHelper.GetColumnStringValue(_workItem, "EncodedAbsUrl");
                    string Thumbnail = SPListHelper.GetColumnStringValue(_workItem, "LISPBlogGalleryThumbnail");
                    int Order = SPListHelper.GetColumnIntValue(_workItem, "LISPBlogGalleryOrder");
                    string Image = string.Format("<img src='{0}' border='0' alt='{1}' />", Thumbnail, Title);
                    if (!string.IsNullOrEmpty(Thumbnail))
                    {
                    PhotoDT.Rows.Add(ID, Title, Url, Image, Order);
                    }


                }
                if (PhotoDT.Rows.Count == 0)
                {
                    PhotoDT.Rows.Add(0, null, null, null, "No Photos found");
                }

                DataSet AlbumDS = new DataSet("Album");
                AlbumDS.Tables.Add(PhotoDT);
                string resultXML = AlbumDS.GetXml();
                transformedXML = SPWebPartHelper.ConvertXML(resultXML, SPContext.Current.Site.Url + XSLTPath);
            }
            else
            {
                DataTable PhotosDT = new DataTable("NoPhotos");
                PhotosDT.Columns.Add("Title");
                PhotosDT.Rows.Add("No Photos Found");
                DataSet AlbumDS = new DataSet("Photos");
                AlbumDS.Tables.Add(PhotosDT);
                string resultXML = AlbumDS.GetXml();
                transformedXML = SPWebPartHelper.ConvertXML(resultXML, SPContext.Current.Site.Url + XSLTPath);
            }


        }
    }
}
